/*
  * 目录：
  * parseTime     --- 时间日期格式化
  * calcNumName   --- 阿拉伯数字转汉字
  * formatTime    --- 时间进度格式化
  * isJSON        --- 判断是否为JSON
  * deepClone     --- 深克隆
  * findValByKey  --- 获取key对应的val
  * createDownloadLink  --- 文件流下载
  * distinct      --- 数组去重
  * repoVsArr     --- 数组求交集
  * diffVsArr     --- 数组求差
  * createRandomId  --- 生成随机id
  * getHost       --- 获取host
  * isNull        --- 判断值是否为空,包括空[],{},'',不包括0
  * throttle      --- 函数节流
  * debounce      --- 函数防抖
  * limitStr      --- 字符串长度限制
  * fullUrl       --- 生成文件路径
  * transformFilesForUpload --- 附件格式装换（填充时）
  * getSingleIframe --- 获取Iframe单例
  * closeWindow   --- 关闭当前窗口
*/
import { useWindow } from '@/micro-app/index'

export function noop () { }

/**
 * @description: 时间日期格式化
 * @param {*} time 时间
 * @param {*} cFormat 所需格式 如：yyyy-mm-dd   y年m月d日h时i分s秒a星期
 * @return {*} timeStr 所需格式的时间字符串
 */
export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  if (!time) return ''
  const format = cFormat || 'yyyy-mm-dd hh:ii:ss'
  let date
  if (typeof time === 'object') {
    date = time
  } else if (typeof time === 'string') {
    date = new Date(time)
  } else {
    time = parseInt(time)
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const timeStr = format.replace(/(y|m|d|h|i|s|a)+/gi, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') { return ['一', '二', '三', '四', '五', '六', '日'][value - 1] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return timeStr
}

/**
 * 数字转汉字
 * @param {*} num 阿拉伯数字
 */
export function calcNumName (num) {
  const changeNum = [
    '零',
    '一',
    '二',
    '三',
    '四',
    '五',
    '六',
    '七',
    '八',
    '九'
  ]
  const unit = ['', '十', '百', '千', '万']
  num = parseInt(num)
  const getWan = temp => {
    const strArr = temp
      .toString()
      .split('')
      .reverse()
    let newNum = ''
    for (var i = 0; i < strArr.length; i++) {
      newNum =
        (i === 0 && strArr[i] === '0'
          ? ''
          : i > 0 && strArr[i] === '0' && strArr[i - 1] === '0'
            ? ''
            : changeNum[strArr[i]] + (strArr[i] === '0' ? unit[0] : unit[i])) +
        newNum
    }
    return newNum
  }
  const overWan = Math.floor(num / 10000)
  let noWan = num % 10000
  if (noWan.toString().length < 4) {
    noWan = '0' + noWan
  }
  return overWan ? getWan(overWan) + '万' + getWan(noWan) : getWan(num)
}

/**
 * @description: 时间进度格式化
 * @param {*} time 时间
 * @param {*} option 如果需要按照【时间日期格式化】的类型返回
 * @return {*} 格式化之后的字符串
 */
export function formatTime (time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @description: 判断是否为JSON
 * @param {*} val
 * @return {*}
 */
export function isJSON (val) {
  if (typeof val !== 'string') {
    return false
  }
  try {
    const obj = JSON.parse(val)
    if (Object.prototype.toString.call(obj) === '[object Object]') {
      return true
    } else {
      return false
    }
  } catch (e) {
    return false
  }
}

const toString = Object.prototype.toString
/**
 * @description: 深克隆
 * @param {*} o 要克隆的obj
 * @return {*} 克隆后的obj
 */
export function deepClone (o) {
  const c = toString.call(o) === '[object Array]' ? [] : {}
  for (const i in o) {
    if (toString.call(o[i]) === '[object Object]') {
      c[i] = deepClone(o[i])
    } else if (Array.isArray(o[i])) {
      c[i] = deepClone(o[i])
    } else {
      c[i] = o[i]
    }
  }
  return c
}

export function ext () {
  // eslint-disable-next-line
  var target = arguments[0] || {},
    i = 1,
    length = arguments.length,
    deep = false,
    options,
    name,
    src,
    copy
  if (typeof target === 'boolean') {
    deep = target
    target = arguments[1] || {}
    i = 2
  }
  if (typeof target !== 'object' && typeof target !== 'function') {
    target = {}
  }
  if (length === i) {
    target = this
    --i
  }
  for (; i < length; i++) {
    if ((options = arguments[i]) != null) {
      for (name in options) {
        src = target[name]
        copy = options[name]
        if (target === copy) {
          continue
        }
        if (
          deep &&
          copy &&
          (typeof copy === 'object' || Array.isArray(copy)) &&
          !copy.nodeType
        ) {
          var clone =
            src && (typeof src === 'object' || Array.isArray(src))
              ? src
              : Array.isArray(copy)
                ? []
                : {}
          target[name] = ext(deep, clone, copy)
        } else if (copy !== undefined) {
          target[name] = copy
        }
      }
    }
  }
  return target
}

/**
 * @description: 获取key对应的val
 * @param {*} data
 * @param {*} val
 * @param {*} key
 * @param {*} childrenKey
 * @return {*}
 */
export function findValByKey (data, val, key = 'id', childrenKey = 'children') {
  for (const i in data) {
    if (data[i][key] && data[i][key] === val) {
      return data[i]
    }
    if (data[i][childrenKey] && data[i][childrenKey].length) {
      var result = findValByKey(data[i][childrenKey], val, key, childrenKey)
      if (result !== undefined) return result
    }
  }
}

/**
 * @description: 文件下载
 * @param {*} res 文件流
 * @return {*} 直接下载文件
 */
export function createDownloadLink (res = {}) {
  const downloadLink = useWindow().document.createElement('a')
  const fileName =
    res.headers &&
    Reflect.has(res.headers, 'content-disposition') &&
    res.headers['content-disposition'].match(/filename="(.+)"/)[1]
  const fileUrl = res.data && useWindow().URL.createObjectURL(res.data)
  downloadLink.href = fileUrl
  downloadLink.download = fileName
  document.body.appendChild(downloadLink)
  downloadLink.click()
  document.body.removeChild(downloadLink)
  useWindow().URL.revokeObjectURL(fileUrl)
}

// export function loadComponent(url) {
//   if (process.env.NODE_ENV === 'development') {
//     return require('@/views' + url).default
//   } else {
//     return () => import('@/views' + url)
//   }
// }

/**
 * Remove an item from an array
 */
export function remove (arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

/**
 * @description: 数组去重
 * @param {*} a 数组一
 * @param {*} b 数组二
 * @param {*} id 判重标志
 * @return {*} 去重后的数组
 */
export function distinct (a, b, id) {
  const arr = a.concat(b)
  const arrId = []
  const result = []
  for (const i of arr) {
    if (arrId.length) {
      if (!arrId.includes(i[id])) {
        arrId.push(i[id])
        result.push(i)
      }
    } else {
      arrId.push(i[id])
      result.push(i)
    }
  }
  return result
}

// 数组求交集
export function repoVsArr (arr1, arr2, id) {
  const tempArr = []

  for (let i = 0; i < arr1.length; i++) {
    const fArr = arr1[i]
    for (let y = 0; y < arr2.length; y++) {
      const sArr = arr2[y]
      if (fArr[id] === sArr[id]) {
        tempArr.push(sArr)
        break
      }
    }
  }
  return tempArr
}

// 数组求差
export function diffVsArr (arr1, arr2, id) {
  const tempArr = arr1.slice()

  for (let i = 0; i < arr1.length; i++) {
    const fArr = arr1[i]
    for (let y = 0; y < arr2.length; y++) {
      const sArr = arr2[y]
      if (fArr[id] === sArr[id]) {
        let tempIndex
        tempArr.filter((_v, index) => {
          if (fArr[id] === _v[id]) tempIndex = index
        })

        tempArr.splice(tempIndex, 1)
        break
      }
    }
  }
  return tempArr
}

/**
 * @description: 生成随机id
 * @return: id
 */
export function createRandomId () {
  return (
    (Math.random() * 10000000).toString(16).substr(0, 4) +
    '-' +
    new Date().getTime() +
    '-' +
    Math.random()
      .toString()
      .substr(2, 5)
  )
}

/**
 * @description: 获取host
 * @return: host
 */
export function getHost () {
  var _http = location.protocol
  var _hostname = location.hostname
  var _port = location.port
  var http = _http + '//' + _hostname + '/'
  if (_port) {
    http = _http + '//' + _hostname + ':' + _port + '/'
  }
  return http
}

/**
 * @description: 判断值是否为空,包括空[],{},'',不包括0
 * @param {str} 所需判断的值
 * @return: Boolean 是否为空
 */
export function isNull (str) {
  if (str === undefined || str === null || str === '') {
    return true
  } else if (Array.isArray(str) && str.length === 0) {
    return true
  } else if (typeof str === 'object' && Object.keys(str).length === 0) {
    return true
  }

  return false
}

/**
 * @description 函数节流
 * @param {Function} fn 需要执行函数节流的函数
 * @param {Number} wait 指定间隔时间
 */
export function throttle (fn, wait = 300) {
  let timer = null
  return function () {
    // 当我们发现这个定时器存在时，则表示定时器已经在运行中，需要返回
    if (timer) return
    timer = setTimeout(() => {
      fn.apply(this, arguments)
      timer = null
    }, wait)
  }
}

// 防抖
export function debounce (fn, wait = 300) {
  var timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, wait)
  }
}

export function getDuration (second) {
  // second = 100000;
  // var days = Math.floor(second / 86400);
  var hours =
    24 * Math.floor(second / 86400) + Math.floor((second % 86400) / 3600)
  var minutes = Math.floor(((second % 86400) % 3600) / 60)
  var seconds = Math.floor(((second % 86400) % 3600) % 60)
  // var duration = days + "天" + hours + "小时" + minutes + "分" + seconds + "秒";
  return [0, hours, minutes, seconds]
}

export function transFromTime (duration) {
  let res = ''
  let isBegin = false
  duration.forEach((item, index) => {
    if (index === 0) {
      if (item > 0) {
        res += item + 'd '
        isBegin = true
      }
    } else if (index === 1) {
      if (isBegin) {
        res += item + 'h '
      } else if (item > 0) {
        res += item + 'h '
        isBegin = true
      }
    } else if (index === 2) {
      if (isBegin) {
        res += item + "'"
      } else if (item > 0) {
        res += item + "'"
        isBegin = true
      }
    } else if (index === 3) {
      if (isBegin) {
        res += item + '"'
      } else if (item > 0) {
        res += item + '"'
        isBegin = true
      }
    }
  })
  return res
}

// 字符串长度限制
export function limitStr (str, length = 8) {
  str = str || ''
  if (str.length > length) {
    return str.slice(0, length) + '...'
  } else {
    return str
  }
}

/**
 * 生成文件路径
 */
export function fullUrl (src) {
  const flleURL = process.env.VUE_APP_BASE_URL
  // http 或者https 或者 blob:http blob:https 开头的
  const rx = /(^https?)|(^blob:https?):\/\//i
  return rx.test(src) ? src : flleURL + src
}

/**
 * 附件格式装换（填充时）
 * @param {array} fileList
 */
export function transformFilesForUpload (fileList = []) {
  return fileList.map(item => {
    return {
      name: item.fileName,
      url: fullUrl(item.path),
      phase: item.phase,
      status: 'success',
      response: {
        data: item.path
      }
    }
  })
}

/**
 * 获取Iframe单例
 * @param {string} src url地址
 */
export const getSingleIframe = (function () {
  let iframe
  return function (src) {
    if (iframe) {
      iframe.src = src
      return iframe
    }
    iframe = document.createElement('iframe')
    iframe.style = 'display:none'
    iframe.src = src
    document.body.appendChild(iframe)
    return iframe
  }
})()

// 关闭当前窗口
export function closeWindow () {
  const userAgent = navigator.userAgent
  if (
    userAgent.indexOf('Firefox') !== -1 ||
    userAgent.indexOf('Chrome') !== -1
  ) {
    location.href = 'about:blank'
    useWindow().close()
  } else {
    location.replace('about:blank')
    useWindow().opener = null
    useWindow().open('', '_self')
    useWindow().close()
  }
}

// 树形接口查找上级

export function treeFindPath (tree, func, path = [], filed = 'id') {
  if (!tree) return []
  for (const data of tree) {
    // 这里按照求来存放最后返回的内容
    path.push(data[filed])
    if (func(data)) return path
    if (data.childNode) {
      const findChildren = treeFindPath(data.childNode, func, path, filed)
      if (findChildren.length) return findChildren
    }
    path.pop()
  }
  return []
}

// tree树型结构数据转list
export function treeToList (treeData, list) {
  if (!Array.isArray(treeData)) {
    return
  }
  treeData.forEach(item => {
    list.push({ ...item, childNode: undefined })
    treeToList(item.childNode, list)
  })
}

/**
 * @returns {string}
 * @param districtNo {stirng} 6位数地区编码.
 * 获取事项编码随机数
 * 唯一，默认自动生成，可修改。规则：6位地区编码+2位日期+4位16进制随机数
 */
export function getRandomCode (districtNo) {
  let dayNum = new Date().getDate()
  if (dayNum < 10) {
    dayNum = '0' + dayNum // 补齐
  }
  const randomNum = Math.random().toString(16).substr(-4)
  const randomCode = districtNo + dayNum + randomNum
  return randomCode
}

export const color = [
  '#2A9CFF',
  '#11C372',
  '#FDAD43',
  '#ff4069',
  '#8355f7',
  '#0055fe',
  '#ff9327',
  '#c022ed',
  '#27D546',
  '#00C9EC'
]
